package net.chasing.androidbaseconfig.widget.rich.base;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;

import androidx.annotation.NonNull;

import net.chasing.androidbaseconfig.widget.rich.RichTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 注：该类未适配多线程操作逻辑，暂时统一在主线程UI线程中调用
 */
public class RichParserManager {
    public static final int RICH_TEXT_COLOR =  0xff0fa8eb;
    //避免重复添加，产生多余操作占用内存资源
    private final HashMap<String, IRichParser> mRichParsers;

    private RichParserManager() {
        mRichParsers = new HashMap<>();
    }

    private static final class MInstanceHolder {
        static final RichParserManager mInstance = new RichParserManager();
    }

    public static RichParserManager getInstance() {
        return MInstanceHolder.mInstance;
    }

    /**
     * 最好直接在Application直接进行注册添加，避免重复添加注册
     * 添加过滤器
     */
    public void registerRichParser(String parserName, IRichParser richParser) {
        if (!mRichParsers.containsKey(parserName))
            mRichParsers.put(parserName, richParser);
    }

    // 解析字符串中的富文本并返回一个经过格式化的富文本串
    public SpannableStringBuilder parseRichItems(Context context, String targetStr) {
        if (containsRichItem(targetStr)) {
            String tempStr = targetStr;
            String richStr = getFirstRichItemText(tempStr);
            SpannableStringBuilder ssb = new SpannableStringBuilder();
            while (!TextUtils.isEmpty(richStr)) {
                //获取富文本首字符下标
                int index = tempStr.indexOf(richStr);
                String startStr = tempStr.substring(0, index);
                ssb.append(startStr);
                //rich string
                ssb.append(formatRichStr(context, richStr));
                //循环
                tempStr = tempStr.substring(index + richStr.length());
                richStr = getFirstRichItemText(tempStr);
            }
            //end String
            ssb.append(tempStr);
            return ssb;
        } else return new SpannableStringBuilder(targetStr);
    }

    public SpannableString setClickableSpan(String text, List<RichItem> changeRichList){
        SpannableString spannableString = new SpannableString(text);
        ClickableSpan clickableSpan;
        for (final RichItem richItem : changeRichList) {
            clickableSpan = new ClickableSpan() {
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    ds.setColor(RICH_TEXT_COLOR);
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(@NonNull View view) {
                    if (RichTextView.isLongClick()) {
                        RichTextView.setIsLongClick(false);
                    }
                }
            };
            if (spannableString.length() >= richItem.getEndPosition())
                spannableString.setSpan(clickableSpan, richItem.getStartPosition(),
                        richItem.getEndPosition(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    //因为计算的是转换后的下标，每次获取完前一个，都会进行文本转换，长度都会进行变更
    //所以需要循环遍历，进行逐个转换获取
    public List<RichItem> getAllSimpleRichItem(Context context, String targetStr) {
        if (containsRichItem(targetStr)) {
            ArrayList<RichItem> richItemList = new ArrayList<>();

            String tempStr = targetStr;
            String richStr = getFirstRichItemText(tempStr);
            StringBuilder sb = new StringBuilder();
            String richText;
            RichItem richItem;
            while (!TextUtils.isEmpty(richStr)) {
                //获取富文本首字符下标
                int index = tempStr.indexOf(richStr);
                String startStr = tempStr.substring(0, index);
                sb.append(startStr);
                richText = sb + richStr;
                richItem = getFirstSimpleRichItem(richText);
                sb.append(formatRichStr(context, richStr));
                tempStr = tempStr.substring(index + richStr.length());
                richStr = getFirstRichItemText(tempStr);
                richItemList.add(richItem);
            }

            return sort(richItemList);
        } else return new ArrayList<>();
    }

    //获取所有富文本item，对应的下标是转换前的下标
    public List<RichItem> getAllRichItem(String targetStr) {
        if (containsRichItem(targetStr)) {
            ArrayList<RichItem> richItemList = new ArrayList<>();

            for (IRichParser richItem : mRichParsers.values()) {
                //遍历mRichItems进行各种操作时,一定要重置targetStr
                richItem.resetTargetStr(targetStr);
                richItemList.addAll(richItem.getAllRichItem());
            }

            return sort(richItemList);
        } else return new ArrayList<>();
    }

    /**
     * 判断是否包含富文本
     */
    public boolean containsRichItem(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        for (IRichParser richItem : mRichParsers.values()) {
            richItem.resetTargetStr(str);
            if (richItem.containsRichItem()) {
                return true;
            }
        }
        return false;
    }

    //将传进来的富文本转换成对应的简单文本，如果不是富文本，则返回""
    public String parserLabelTextToRich(String targetStr) {
        for (IRichParser richItem : mRichParsers.values()) {
            richItem.resetTargetStr(targetStr);
            if (richItem.containsRichItem()) {
                return richItem.parserLabelTextToRich(targetStr);
            }
        }
        return "";
    }

    //对数据按RichItem的startPosition从小到大进行排序
    private List<RichItem> sort(ArrayList<RichItem> richItemList) {
        RichItem temp;
        for (int i = 0; i < richItemList.size() - 1; i++) {
            for (int j = i + 1; j < richItemList.size(); j++) {
                if (richItemList.get(j).getStartPosition() < richItemList.get(i).getStartPosition()) {
                    temp = richItemList.get(i);
                    richItemList.set(i, richItemList.get(j));
                    richItemList.set(j, temp);
                }
            }
        }
        return richItemList;
    }

    // 将String数据转换成相应的富文本SpannableString
    private SpannableString formatRichStr(Context context, String richStr) {
        for (IRichParser richItem : mRichParsers.values()) {
            //遍历mRichItems进行各种操作时,一定要重置targetStr
            richItem.resetTargetStr(richStr);
            if (richItem.containsRichItem()) {
                return richItem.getRichSpannable(context);
            }
        }
        return new SpannableString(richStr);
    }

    /**
     * 获取字符串中的第一个富文本串
     *
     * @return 第一个"话题"或者第一个"@"或者其他,如果没有富文本串,则返回空字符串("")
     */
    private String getFirstRichItemText(String targetStr) {
        int index = Integer.MAX_VALUE;
        IRichParser iRichParser = null;
        int temp;
        for (IRichParser richItem : mRichParsers.values()) {
            //遍历mRichItems进行各种操作时,一定要重置targetStr
            richItem.resetTargetStr(targetStr);
            temp = richItem.getFirstRichIndex();
            if (temp < index && temp != -1) {
                index = temp;
                iRichParser = richItem;
            }
        }
        return iRichParser == null ? "" : iRichParser.getFirstRichItemText();
    }

    private RichItem getFirstSimpleRichItem(String targetStr) {
        int index = Integer.MAX_VALUE;
        IRichParser iRichParser = null;
        int temp;
        for (IRichParser richItem : mRichParsers.values()) {
            //遍历mRichItems进行各种操作时,一定要重置targetStr
            richItem.resetTargetStr(targetStr);
            temp = richItem.getFirstRichIndex();
            if (temp < index && temp != -1) {
                index = temp;
                iRichParser = richItem;
            }
        }
        return iRichParser == null ? null : iRichParser.getSimpleFirstRichItem();
    }
}
